package com.tencent.qcloud.tim.uikit.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.SdkVersionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class PictureSelectUtils {


    public interface IAddImageListener {//创建抽象类

        void onSelectedPictures(List<LocalMedia> list);//添加抽象方法，可任意添加多个可带参数如void test(String cibtext);往下加就行
    }

    private final static int MIME_TYPE_ALL = PictureMimeType.ofAll();
    public final static int MIME_TYPE_IMAGE = PictureMimeType.ofImage();
    private final static int MIME_TYPE_VIDEO = PictureMimeType.ofVideo();
    private final static int MIME_TYPE_AUDIO = PictureMimeType.ofAudio();


    private boolean IS_COOMPRESS = true;// 是否压缩
    private int IS_COOMPRESS_RATIO = 60;// 图片压缩后输出质量
    private int COMPRESS_SIZE = 100;// 小于100kb的图片不压缩
    private boolean OPEN_CLICK_SOUND = false;// 是否开启点击声音

    /**
     * 选择拍照
     */
    public void selectCamera(Activity activity, List<LocalMedia> localMedia, final IAddImageListener listener) {

        PictureSelector.create(activity)
                .openCamera(MIME_TYPE_IMAGE)// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .selectionData(localMedia)// 是否传入已选图片
                .isCamera(true)// 是否显示拍照按钮
                .isGif(false)
                .isOpenClickSound(OPEN_CLICK_SOUND)// 是否开启点击声音
                .isCompress(IS_COOMPRESS)// 是否压缩
                .compressQuality(IS_COOMPRESS_RATIO)// 图片压缩后输出质量
                .minimumCompressSize(COMPRESS_SIZE)// 小于100kb的图片不压缩
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // 结果回调
                        listener.onSelectedPictures(result);
                    }

                    @Override
                    public void onCancel() {
                        // 取消

                    }
                });

    }

    /**
     * 选择本地相册
     */
    public void selectLocalImg(final Activity activity, List<LocalMedia> localMedia, int maxNum, int minNum, final IAddImageListener listener) {

        PictureSelector.create(activity)
                .openGallery(MIME_TYPE_IMAGE)
                .imageEngine(TGlideEngine.createGlideEngine())
                .minSelectNum(minNum)
                .maxSelectNum(maxNum)
                .selectionData(localMedia)
                .isCamera(true)
                .isGif(false)
                .isCamera(false)// 是否显示拍照按钮
                .isOpenClickSound(OPEN_CLICK_SOUND)
                .isCompress(IS_COOMPRESS)// 是否压缩
                .compressQuality(IS_COOMPRESS_RATIO)// 图片压缩后输出质量
                .minimumCompressSize(COMPRESS_SIZE)// 小于100kb的图片不压缩

                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // 结果回调
                        for (int i = 0; i < result.size(); i++) {
                            if (SdkVersionUtils.checkedAndroid_Q()) {
                                int degree = readPictureDegree(result.get(i).getAndroidQToPath());
                                if(degree==0){
                                    listener.onSelectedPictures(result);
                                    return;
                                }
                                try {
                                    Bitmap bmpOk = rotateToDegrees( BitmapFactory.decodeFile(result.get(i).getAndroidQToPath()), degree);
                                    result.get(i).setAndroidQToPath(saveImg(bmpOk,"shandui",activity));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else {
                                int degree = readPictureDegree(result.get(i).getPath());
                                if(degree==0){
                                    listener.onSelectedPictures(result);
                                    return;
                                }
                                try {
                                    Bitmap bmpOk = rotateToDegrees( BitmapFactory.decodeFile(result.get(i).getPath()), degree);
                                    result.get(i).setPath(saveImg(bmpOk,"taomi",activity));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        listener.onSelectedPictures(result);
                    }

                    @Override
                    public void onCancel() {
                        // 取消
                    }
                });

    }

    public void takeCamera(Activity activity,final IAddImageListener listener) {
        PictureSelector.create(activity)
                .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .selectionData(null)// 是否传入已选图片
                .isCamera(true)// 是否显示拍照按钮
                .isGif(false)
                .isOpenClickSound(false)// 是否开启点击声音
                .isCompress(false)// 是否压缩
                .isEnableCrop(false)
                .minimumCompressSize(20480)
                .forResult(new OnResultCallbackListener() {
                    @Override
                    public void onResult(List result) {
                        listener.onSelectedPictures(result);
                    }

                    @Override
                    public void onCancel() {

                    }
                });

    }

    /**
     * 读取照片exif信息中的旋转角度
     * @param path        照片路径
     * @return角度
     */
    public int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return degree;

    }
    public static Bitmap rotateToDegrees(Bitmap tmpBitmap, float degrees) throws Exception {
        Matrix matrix = new Matrix();
        matrix.reset();
        matrix.setRotate(degrees);
        return tmpBitmap = Bitmap.createBitmap(tmpBitmap, 0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight(), matrix, true);
    }
    /**
     * 将bitmap作为图片保存到本地并返回保存地址
     * @param b
     * @param name
     * @return
     * @throws Exception
     */
    public static String saveImg(Bitmap b, String name, Context context) throws Exception {
        String path = PictureFileUtils.createFilePath(context, "", "", name);
        File mediaFile = new File(path + System.currentTimeMillis()+name + ".jpg");
        if (mediaFile.exists()) {
            mediaFile.delete();
        }
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        mediaFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(mediaFile);
        b.compress(Bitmap.CompressFormat.PNG, 80, fos);
        fos.flush();
        fos.close();
        b.recycle();
        b = null;
        System.gc();
        return mediaFile.getPath();
    }

}
